package com.cagtwitter.services;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Enumeration;
import java.util.Properties;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.cagtwitter.hibernate.AboutCelebTweet;
import com.cagtwitter.hibernate.AboutTvShowTweet;
import com.cagtwitter.hibernate.CelebTweet;
import com.cagtwitter.hibernate.Celebrity;
import com.cagtwitter.hibernate.CelebrityDao;
import com.cagtwitter.hibernate.TvShowDao;



public class WebDataServices {
	public String getUrlSource(String urlString){
		URL url;
		BufferedReader in;
		String source = "",line = "";
		
		try {
			url = new URL(urlString);
			
			in = new BufferedReader(
					new InputStreamReader(
					url.openStream()));
			while ((line = in.readLine()) != null)
			    source += line;
			in.close();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return source;
	}
	
	public String getJsonFromUrl(String url,Properties properties){
		String urlString = url;
		int count = 0;
		String key="";
		//System.out.println(properties.getProperty("count"));
		Enumeration enProps = properties.propertyNames();
		
		while(enProps.hasMoreElements()){
			count++;
			key = (String) enProps.nextElement();
			if(count > 1) urlString += "&";
			urlString += key + "=" +properties.getProperty(key);
		}
		
		return getUrlSource(urlString);
	}
	
	public String getUserData(String screen_name){
		return getUrlSource(BaseParams.USER_DETAILS + BaseParams.SCREEN_NAME + "=" + screen_name);
	}
	
	public String getUserTimeline(String screen_name,Properties properties){
		String url = BaseParams.USER_TIMELINE + BaseParams.SCREEN_NAME + "=" + screen_name + "&";
		
		return getJsonFromUrl(url,properties);
	}
	
	public String getTweetsAboutUser(String screen_name,String page){
		String url = BaseParams.TWEETS_ABOUT_USER +BaseParams.QUERY_PARAM_TWEETS_ABOUT_USER + "=" + screen_name + "&" + BaseParams.PAGE + "=" + page;
		
		return getUrlSource(url);
	}
	
	//New
	public String getAboutTweets(String query,Properties properties){
		String url = BaseParams.TWEETS_ABOUT_USER +BaseParams.QUERY_PARAM_TWEETS_ABOUT_USER + "=" + query + "&";
		
		return getJsonFromUrl(url,properties);
	}
	
	// URL to Database
	public void writeCelebTweetsToDB(String screen_name,Properties properties){
		CelebrityDao hbc = new CelebrityDao();
		try {
			JSONArray sourceJSON = new JSONArray(getUserTimeline(screen_name,properties));
			
			for(int i=0;i < sourceJSON.length(); i++){
				CelebTweet celebTweet = new CelebTweet();
				
				JSONObject json = sourceJSON.getJSONObject(i);
				
				celebTweet.setName(screen_name);
				
				if(json.isNull("retweeted_status") == false){ //if retweeted
					if(hbc.isAnyCelebTweetWithId(json.getJSONObject("retweeted_status").getString("id"),"CelebTweet") == false){
						if(i == 0) hbc.setLastTwid(screen_name,json.getJSONObject("retweeted_status").getString("id"),"celeb");
						celebTweet.setTweetdate(json.getJSONObject("retweeted_status").getString("created_at"));
						celebTweet.setTweetfullname(json.getJSONObject("retweeted_status").getJSONObject("user").getString("name"));
						celebTweet.setTweetimg(json.getJSONObject("retweeted_status").getJSONObject("user").getString("profile_image_url"));
						celebTweet.setTweetname(json.getJSONObject("retweeted_status").getJSONObject("user").getString("screen_name"));
						celebTweet.setTweettext(json.getJSONObject("retweeted_status").getString("text"));
						celebTweet.setTwid(json.getJSONObject("retweeted_status").getString("id"));
						
						hbc.addCelebrityTweet(celebTweet);
					}

				}
				else{
					if(hbc.isAnyCelebTweetWithId(json.getString("id"),"CelebTweet") == false){
						if(i == 0) hbc.setLastTwid(screen_name,json.getString("id"),BaseParams.CELEBRITY);
						celebTweet.setTweetdate(json.getString("created_at"));
						celebTweet.setTweetfullname(json.getJSONObject("user").getString("name"));
						celebTweet.setTweetimg(json.getJSONObject("user").getString("profile_image_url"));
						celebTweet.setTweetname(json.getJSONObject("user").getString("screen_name"));
						celebTweet.setTweettext(json.getString("text"));
						celebTweet.setTwid(json.getString("id"));
						
						hbc.addCelebrityTweet(celebTweet);
					}
					
				}
				
			}
			
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void writeAboutCelebTweetsToDB(Celebrity celeb,Properties properties){
		CelebrityDao hbc = new CelebrityDao();
		MiscServices miscServ = new MiscServices();
		try {
			JSONObject resultJson = new JSONObject(getAboutTweets(miscServ.toSearchQuery(celeb.getFirstName() + " " + celeb.getLastName()), properties));
			JSONArray sourceJSON = new JSONArray(resultJson.getString("results"));
			
			for(int i=0;i < sourceJSON.length(); i++){
				
				AboutCelebTweet aboutCelebTweet = new AboutCelebTweet();
				JSONObject json = sourceJSON.getJSONObject(i);
				
				if(hbc.isAnyCelebTweetWithId(json.getString("id"),"AboutCelebTweet") == false){
					aboutCelebTweet.setName(celeb.getUsername());
					
					if(i == 0) hbc.setLastTwid(celeb.getUsername(),json.getString("id"),BaseParams.ABOUT);
					aboutCelebTweet.setTweetdate(json.getString("created_at"));
					aboutCelebTweet.setTweetfullname(json.getString("from_user"));
					aboutCelebTweet.setTweetimg(json.getString("profile_image_url"));
					aboutCelebTweet.setTweetname(json.getString("from_user"));
					aboutCelebTweet.setTweettext(json.getString("text"));
					aboutCelebTweet.setTwid(json.getString("id"));
					
					hbc.addAboutCelebrityTweet(aboutCelebTweet);
				}
			}
			
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	public void writeAboutTvShowTweetsToDB(String name,Properties properties){
		CelebrityDao hbc = new CelebrityDao();
		TvShowDao hbtv = new TvShowDao();
		MiscServices msc = new MiscServices();
		String queryName = msc.toSearchQuery(name);
		try {
			JSONObject resultJson = new JSONObject(getAboutTweets(queryName, properties));
			JSONArray sourceJSON = new JSONArray(resultJson.getString("results"));
			
			for(int i=0;i < sourceJSON.length(); i++){
				AboutTvShowTweet aboutTvShowTweet = new AboutTvShowTweet();
				JSONObject json = sourceJSON.getJSONObject(i);
				
				if(hbc.isAnyCelebTweetWithId(json.getString("id"),"AboutTvShowTweet") == false){
					aboutTvShowTweet.setName(msc.toId(name));
					if(i == 0) hbtv.setLastTwid(name,json.getString("id"),BaseParams.ABOUT);
					aboutTvShowTweet.setTweetdate(json.getString("created_at"));
					aboutTvShowTweet.setTweetfullname(json.getString("from_user"));
					aboutTvShowTweet.setTweetimg(json.getString("profile_image_url"));
					aboutTvShowTweet.setTweetname(json.getString("from_user"));
					aboutTvShowTweet.setTweettext(json.getString("text"));
					aboutTvShowTweet.setTwid(json.getString("id"));
					
					hbtv.addAboutTvShowTweet(aboutTvShowTweet);
				}
				
				
			}
			
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
